<?php

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Services\Helper;
use Validator;
use DB;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PersonalController extends Controller
{    	
    public function index() 
    {	                 
    	$uid = session('uid'); 
        if (!empty($uid)) {  
        	$user = DB::select('SELECT username, birthday, gender, nickname, profession, signature, phone, photo, address FROM users WHERE users.uid ="'.$uid.'"');
        	$user['pic'] = DB::select('SELECT url FROM `picture` WHERE uid ="'.$uid.'"');

            return Helper::jsonSuccess('获取成功', $user);
        }else {
        	return Helper::jsonError('未登录，请先登录');
        }
    }   

	protected function validator(array $data, $uid)
    {
        $messages = [
            'nickname.required' => '别名必须填写',
            'nickname.unique' => '别名已占用',
            'nickname.min' => '别名最小包含6个字符',

            'phone.required' => '手机必须填写',
            'phone.phone' => '手机格式不正确',
            'phone.unique' => '手机已经被占用',
        ];

        return Validator::make($data, [           
            'nickname' => [
            	'required',
            	'min:3',
            	Rule::unique('users')->ignore($uid, 'uid'),
            ],       
            'phone' => [
            	'required',
            	'phone',
            	Rule::unique('users')->ignore($uid, 'uid'),
            ],
        ],$messages);
    }     

	public function change(Request $request) 
    {	        	
        $uid = session('uid'); 
        $data['nickname'] = $request->input('nickname');
        $data['birthday'] = $request->input('birthday');
        $data['phone'] = $request->input('phone');
        $data['address'] = $request->input('address');
        $data['gender'] = $request->input('gender');
        $data['profession'] = $request->input('profession');
        $data['signature'] = $request->input('signature');

        $validatorMsg = $this->validator($data, $uid);
 		if ($validatorMsg->fails()) {
            return Helper::jsonError($validatorMsg->errors()->first());
        }        

		$result = $this->update($data, $uid);

        if ($result) {                
            //更新密码               
            return Helper::jsonSuccess('信息修改成功');      
        } else {
            return Helper::jsonError('信息修改成功');
        }     
    }

    protected function update(array $data , $uid)
    { 	
        return  DB::table('users')->where('uid', $uid)->update([
        	'nickname' =>$data['nickname'],
        	'birthday' =>$data['birthday'],
        	'address' =>$data['address'],
        	'phone' =>$data['phone'],
        	'gender' => '1',
        	'profession' =>$data['profession'],
        	'signature' =>$data['signature'],
        ]);
    }


}
